package com.example.boke.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.boke.entity.*;
import com.example.boke.mapper.*;
import com.example.boke.service.impl.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.PublicKey;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-04-16
 */

@Controller
@RequestMapping("/admin")
public class BlogController {

    @Autowired
    private BlogServiceImpl blogServiceimpl;

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private BlogTagServiceImpl blogTagServiceimpl;

    @Autowired
    private BlogTagMapper blogTagsMapper;

    @Autowired
    private TypeServiceImpl typeServiceimpl;

    @Autowired
    private TypeMapper typeMapper;

    private TagServiceImpl tagServiceimpl;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private UserServiceImpl userserviceimpl;

    @Autowired
    private UserMapper userMapper;


    @GetMapping(value = "/blog")
    public String blog(HttpSession session, Model model)
    {
        long userId = (long) session.getAttribute("id");

        Page<Blog> blogPage = new Page<>(1,5);

        QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();

        blogQueryWrapper.eq("user_id",userId).orderByDesc("create_time");
        typeQueryWrapper.eq("user_id",userId);

        List<Type> types = typeMapper.selectList(typeQueryWrapper);

        blogMapper.selectPage(blogPage,blogQueryWrapper);
        List<Blog> blogs = blogPage.getRecords();


        List<SimplifyBlog> simplifyBlogList = new ArrayList<>();

        blogs.forEach(blog -> {
            SimplifyBlog simplifyBlog = new SimplifyBlog();

            simplifyBlog.setId(blog.getId());
            simplifyBlog.setPublished(blog.getPublished());
            simplifyBlog.setRecommend(blog.getRecommend());
            simplifyBlog.setTitle(blog.getTitle());
            simplifyBlog.setTypename(typeMapper.selectById(blog.getTypeId()).getName());
            String updateTime = blog.getUpdateTime()+"";
            int length = updateTime.length();
            simplifyBlog.setUpdatetime(updateTime.substring(0,length-7).replaceAll("T"," "));
            simplifyBlogList.add(simplifyBlog);
        });



        model.addAttribute("typelist",types);
        model.addAttribute("bloglist",simplifyBlogList);
        model.addAttribute("pc", blogPage.getCurrent());//第几页
        model.addAttribute("hasPrevious",blogPage.hasPrevious());//是否有上一页
        model.addAttribute("hasNext",blogPage.hasNext());//是否有下一页
        return "admin/blogs";
    }

    @PostMapping(value = "/findblog")
    public String findblog(@RequestParam(required = false) String title,
                           @RequestParam(required = false) Long typeId,
                           @RequestParam(required = false) Boolean recommend,
                           @RequestParam(required = false) Boolean published ,
                           HttpSession session, Model model,
                           Integer pc){
        if (recommend != null)
        {
            System.out.println("是否推荐：" + (recommend ? "是" : "否"));
        }

        if (published != null)
        {
            System.out.println("发布状态："+  (published ? "发布" : "保存"));
        }

        if (pc == null)
        {
            pc = 1;
        }
        long userId = (long) session.getAttribute("id");

        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        Map<String,Object> map = new HashMap<>();

        map.put("title", title);
        map.put("type_id", typeId);
        map.put("recommend", recommend);
        map.put("published",published);
        map.put("user_id", userId);

        blogQueryWrapper.select("id", "title", "type_id", "recommend", "update_time","published").allEq(map, false).orderByDesc("create_time");

        Page<Blog> blogPage = new Page<>(pc,5);

        blogMapper.selectPage(blogPage, blogQueryWrapper);

        List<Blog> blogs = blogPage.getRecords();

        List<SimplifyBlog> simplifyBlogList = new ArrayList<>();

        blogs.forEach(blog -> {
            SimplifyBlog simplifyBlog = new SimplifyBlog();

            simplifyBlog.setId(blog.getId());
            simplifyBlog.setPublished(blog.getPublished());
            simplifyBlog.setRecommend(blog.getRecommend());
            simplifyBlog.setTitle(blog.getTitle());
            simplifyBlog.setTypename(typeMapper.selectById(blog.getTypeId()).getName());
            String updateTime = blog.getUpdateTime()+"";
            int length = updateTime.length();
            simplifyBlog.setUpdatetime(updateTime.substring(0,length-7).replaceAll("T"," "));


            simplifyBlogList.add(simplifyBlog);

        });
        model.addAttribute("bloglist",simplifyBlogList);
        model.addAttribute("pc", blogPage.getCurrent());//第几页
        model.addAttribute("hasPrevious",blogPage.hasPrevious());//是否有上一页
        model.addAttribute("hasNext",blogPage.hasNext());//是否有下一页



        return "admin/blogs :: blogList";
    }


    @PostMapping(value = "/removeblog")
    public String removeblog(@RequestParam(required = false) String title,
                           @RequestParam(required = false) Long typeId,
                           @RequestParam(required = false) Boolean recommend,
                           @RequestParam(required = false) Boolean published ,
                           HttpSession session, Model model,
                           Integer pc,Long blogId){

        long userId = (long) session.getAttribute("id");

        UpdateWrapper<Blog> blogUpdateWrapper = new UpdateWrapper<>();
        blogUpdateWrapper.eq("id",blogId).eq("user_id",userId);

        int delete = blogMapper.delete(blogUpdateWrapper);//删除成功后

        //对应的标签中的表也得删除
        UpdateWrapper<BlogTag> blogTagUpdateWrapper = new UpdateWrapper<BlogTag>();
        blogTagUpdateWrapper.eq("user_id",userId).eq("blogs_id",blogId);

        blogTagsMapper.delete(blogTagUpdateWrapper);

        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        Map<String,Object> map = new HashMap<>();

        map.put("title", title);
        map.put("type_id", typeId);
        map.put("recommend", recommend);
        map.put("published",published);
        map.put("user_id", userId);

        blogQueryWrapper.select("id", "title", "type_id", "recommend", "update_time","published").allEq(map, false);

        Page<Blog> blogPage = new Page<>(pc,5);
        blogMapper.selectPage(blogPage, blogQueryWrapper);

        if (blogPage.getCurrent() > blogPage.getPages())//判断删除界限
        {
            blogPage = new Page<>(blogPage.getCurrent(),5);
            blogMapper.selectPage(blogPage, blogQueryWrapper);

        }

        List<Blog> blogs = blogPage.getRecords();

        List<SimplifyBlog> simplifyBlogList = new ArrayList<>();

        blogs.forEach(blog -> {
            SimplifyBlog simplifyBlog = new SimplifyBlog();

            simplifyBlog.setId(blog.getId());
            simplifyBlog.setPublished(blog.getPublished());
            simplifyBlog.setRecommend(blog.getRecommend());
            simplifyBlog.setTitle(blog.getTitle());
            simplifyBlog.setTypename(typeMapper.selectById(blog.getTypeId()).getName());
            String updateTime = blog.getUpdateTime()+"";
            int length = updateTime.length();
            simplifyBlog.setUpdatetime(updateTime.substring(0,length-7).replaceAll("T"," "));
            simplifyBlogList.add(simplifyBlog);
        });

        model.addAttribute("pc", blogPage.getCurrent());//第几页
        model.addAttribute("bloglist",simplifyBlogList);
        model.addAttribute("hasPrevious",blogPage.hasPrevious());//是否有上一页
        model.addAttribute("hasNext",blogPage.hasNext());//是否有下一页

        return "admin/blogs :: blogList";
    }

    @GetMapping(value = "/blogs-inputtwo")
    public String blogsinputtwo()
    {

        return "admin/blogs-input";
    }

    @GetMapping(value = "/blogs-input")
    public String blogsinput(HttpSession session, RedirectAttributes redirectAttributes)
    {
        long userId = (long) session.getAttribute("id");

        QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();

        typeQueryWrapper.eq("user_id",userId);
        tagQueryWrapper.eq("user_id",userId);


        List<Type> types = typeMapper.selectList(typeQueryWrapper);
        List<Tag> tags = tagMapper.selectList(tagQueryWrapper);

        redirectAttributes.addFlashAttribute("typelist",types);
        redirectAttributes.addFlashAttribute("taglist",tags);

        return "redirect:/admin/blogs-inputtwo";
    }


    @PostMapping(value = "/blogsinput")
    public String blogsinput(Blog blog, Long[] arrs, HttpSession session,RedirectAttributes redirectAttributes) {

        long userId = (long) session.getAttribute("id");

        blog.setUserId(userId);

        LocalDateTime createTime = blog.getCreateTime();

        QueryWrapper<Blog> tBlogQueryWrapper = new QueryWrapper<Blog>();

        if (!blogServiceimpl.save(blog))
        {

            redirectAttributes.addFlashAttribute("message", "新增文章失败");

            return "redriect:/admin/blog";
        }

        //获取刚创建的博客文件的id
        tBlogQueryWrapper.eq("user_id", userId).eq("create_time", createTime);

        Blog tBlog1 = blogMapper.selectOne(tBlogQueryWrapper);

        Long blogId = tBlog1.getId();

        boolean published = tBlog1.getPublished();

        //插入数据进blog_tag库中

        for (Long arr : arrs) {

            BlogTag tBlogTags = new BlogTag();
            tBlogTags.setId(null);
            tBlogTags.setBlogsId(blogId);
            tBlogTags.setTagsId(arr);
            tBlogTags.setUserId(userId);

            blogTagServiceimpl.save(tBlogTags);
        }



        if (published) {

            redirectAttributes.addFlashAttribute("message", "发布成功");

        } else {

            redirectAttributes.addFlashAttribute("message", "保存成功");
        }

        return "redirect:/admin/blog";

    }




    @GetMapping(value = "/updateblogone")
    public String getblog(Long blogId, HttpServletRequest request,RedirectAttributes redirectAttributes) {

        long userId = (long) request.getSession().getAttribute("id");


        QueryWrapper<Blog> tBlogQueryWrapper = new QueryWrapper<>();

        tBlogQueryWrapper.eq("user_id", userId).eq("id", blogId);

        Blog tBlog = blogMapper.selectOne(tBlogQueryWrapper);

        QueryWrapper<Type> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_id", userId);

        List<Type> types = typeMapper.selectList(queryWrapper);


        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();

        tagQueryWrapper.eq("user_id",userId);

        List<Tag> tags = tagMapper.selectList(tagQueryWrapper);

        //获取属于该博客的标签id字符串
        QueryWrapper<BlogTag> blogTagQueryWrapper = new QueryWrapper<>();
        blogTagQueryWrapper.eq("blogs_id",blogId).eq("user_id",userId);
        List<BlogTag> blogTags = blogTagsMapper.selectList(blogTagQueryWrapper);

        StringBuilder blogIdbuffer = new StringBuilder();

        blogTags.forEach(blogTag ->{

            blogIdbuffer.append(blogTag.getTagsId()).append(",");

        });

        redirectAttributes.addFlashAttribute("blogtags",blogIdbuffer.substring(0, (blogIdbuffer.length() - 1)));
        redirectAttributes.addFlashAttribute("blog", tBlog);
        redirectAttributes.addFlashAttribute("typelist", types);
        redirectAttributes.addFlashAttribute("taglist", tags);

        return "redirect:/admin/blogsupdate";


    }

    @GetMapping(value = "/blogsupdate")
    public String blogsupdate()
    {
        return "admin/blogs-update";
    }


    @PostMapping(value = "/updateblog")
    public String updateblog(Blog tBlog, Long[] arrs,HttpServletRequest request,RedirectAttributes redirectAttributes) {

        System.out.println(tBlog);

        long userId = (long) request.getSession().getAttribute("id");

        UpdateWrapper<Blog> blogUpdateWrapper = new UpdateWrapper<>();

        blogUpdateWrapper
                .set("appreciation",tBlog.getAppreciation())
                .set("commentabled",tBlog.getCommentabled())
                .set("content",tBlog.getContent())
                .set("flag",tBlog.getFlag())
                .set("published",tBlog.getPublished())
                .set("recommend",tBlog.getRecommend())
                .set("title",tBlog.getTitle())
                .set("type_id",tBlog.getTypeId())
                .set("update_time",LocalDateTime.now())
                .set("first_picture",tBlog.getFirstPicture())
                .set("share_statement",tBlog.getShareStatement())
                .eq("id",tBlog.getId())
                .eq("user_id",userId);

        int result = blogMapper.update(null,blogUpdateWrapper);

        if ( result != 1 )
        {
            redirectAttributes.addFlashAttribute("message","修改失败");
            return "redirect:/admin/blog";

        }

        //对t_blog_tags库中的数据进行更新：先删除再插入
        UpdateWrapper<BlogTag> tBlogTagsUpdateWrapper = new UpdateWrapper<>();
        tBlogTagsUpdateWrapper.eq("blogs_id",tBlog.getId());

        blogTagsMapper.delete(tBlogTagsUpdateWrapper);

        //再进行插入
        for (Long arr : arrs) {

            BlogTag tBlogTags = new BlogTag();
            tBlogTags.setId(null);
            tBlogTags.setBlogsId(tBlog.getId());
            tBlogTags.setTagsId(arr);
            tBlogTags.setUserId(userId);

            blogTagServiceimpl.save(tBlogTags);
        }

        redirectAttributes.addFlashAttribute("message","更新成功");

        return "redirect:/admin/blog";
    }


//    @PostMapping(value = "/bloginputcomment")
//    @ResponseBody
//    public Map<String,Object> bloginputcomment(Comment comment,HttpServletRequest request)
//    {
//        Map<String, Object> map = new HashMap<>();
//
//        long userId = (long) request.getSession().getAttribute("id");
//
//        String nickname = (String) request.getSession().getAttribute("nickanme");
//
//        comment.setUserId(userId);
//        comment.setUserNickname(nickname);
//
//        if (commentserviceimpl.save(comment)) {
//
//            map.put("state", true);
//            map.put("message", "评论成功");
//
//            QueryWrapper<Comment> tCommentQueryWrapper = new QueryWrapper<>();
//            tCommentQueryWrapper.eq("create_time", comment.getCreateTime());
//
//            Comment tComment = commentMapper.selectOne(tCommentQueryWrapper);
//
//            map.put("comoment", tComment);
//
//
//        }else{
//
//            map.put("state",false);
//            map.put("message","评论失败");
//
//        }
//
//
//        return map;
//    }
//
//    @GetMapping(value = "/getcomment")
////    @ApiOperation(value = "通过博客的id来获取该博客下的所有评论")
//    @ResponseBody
//    public Map<String,Object> getcomment(@RequestParam Long id)
//    {
//
//        Map<String, Object> map = new HashMap<>();
//
//        QueryWrapper<Comment> tCommentQueryWrapper = new QueryWrapper<>();
//        if (!blogServiceimpl.getById(id).getCommentabled())
//        {
//            map.put("state",false);
//            map.put("message","该用户的评论功能已关闭");
//            return map;
//        }
//
//        //首先构造父级评论的信息
//        tCommentQueryWrapper.eq("blog_id",id).eq("superior_id",0);
//
//        //父级评论
//        List<Comment> tComments = commentMapper.selectList(tCommentQueryWrapper);
//
//        List<Object> commentList = new ArrayList<>();
//
//        int count = 1;
//
//        for (Comment tComment : tComments) {
//
//            commentList.add("第"+count+"条父级评论：");
//
//            commentList.add(tComment);
//
//            tCommentQueryWrapper.clear();
//
//            tCommentQueryWrapper.eq("superior_id",tComment.getId());
//
//            if ( commentMapper.selectCount(tCommentQueryWrapper) != 0 )
//            {
//                //这个是子级评论
//                List<Comment> tComments1 = commentMapper.selectList(tCommentQueryWrapper);
//                commentList.add("第"+count+"条评论下的子级评论：");
//                tComments1.forEach(tComment1 -> {
//
//
//
//                    commentList.add(tComment1);
//
//                    tCommentQueryWrapper.clear();
//
//                    tCommentQueryWrapper.eq("superior_id",tComment1.getId());
//
//
//                    while (commentMapper.selectOne(tCommentQueryWrapper) != null)
//                    {
//
//                        Comment tComment2 = commentMapper.selectOne(tCommentQueryWrapper);
//
//                        commentList.add(tComment2);
//
//                        tCommentQueryWrapper.clear();
//
//                        tCommentQueryWrapper.eq("superior_id",tComment2.getId());
//
//                    }
//                });
//
//            }
//
//            count++;
//
//        }
//
//        map.put("state",true);
//        map.put("message","获取成功");
//        map.put("commentList",commentList);
//        commentList.forEach(System.out::println);
//
//        return map;
//
//    }


    @GetMapping(value = "/views")
//    @ApiOperation(value = "处理文章的浏览次数，设置cookie一小时后过期，后端能获取到cookie说明还没过期，浏览次数不会增加，防止恶意刷浏览次数")
    @ResponseBody
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "blogId",value = "被访问的博客文章的id，前端传值",required = true,dataType = "Long"),
//    })
    public Map<String,Object> views(Long blogId, HttpServletRequest request, HttpServletResponse response)
    {
        Map<String, Object> map = new HashMap<>();

        long userId = (long) request.getSession().getAttribute("id");

        //首先检查该博客是否存在
        QueryWrapper<Blog> tBlogQueryWrapper = new QueryWrapper<>();

        tBlogQueryWrapper.eq("id",blogId);

        Integer integer = blogMapper.selectCount(tBlogQueryWrapper);

        if ( integer ==  0)
        {
            map.put("state",false);
            map.put("message","博客不存在");
            return map;
        }


        Cookie[] cookies = request.getCookies();

        for (Cookie cookie : cookies) {

            if (cookie.getName().equals("userId") && cookie.getValue().equals(String.valueOf(userId)))
            {
                //能获到这里说明是用户在一小时之内的重复浏览
                map.put("state",false);
                map.put("message","一小时之内的重复浏览，不会增加浏览次数");
                return map;
            }

        }

        //能到下面的就说明cookie过期,获取

        QueryWrapper<Blog> tBlogQueryWrapper1 = new QueryWrapper<>();

        tBlogQueryWrapper1.select("user_id","views").eq("id",blogId);

        Blog tBlog = blogMapper.selectOne(tBlogQueryWrapper1);

        Long resultUserid = tBlog.getUserId();

        if (resultUserid.equals(userId))
        {
            map.put("state",false);
            map.put("message","查看自身的文章，浏览次数不会进行增加");
            return map;
        }

        //如果该文章存在且操作人不是用户本人，就进行逻辑处理

        Cookie cookie = new Cookie("userId",String.valueOf(userId));

        cookie.setMaxAge(60*60);//设置过期时间，如果是重复观看，那么时间得过一小时后才能对浏览次数加一

        //对该博客的浏览次数进行修改

        UpdateWrapper<Blog> blogUpdateWrapper = new UpdateWrapper<>();

        blogUpdateWrapper.set("views",tBlog.getViews()+1).eq("id",blogId);

        int result  = blogMapper.update(null, blogUpdateWrapper);

        if (result == 1)
        {

            map.put("state",true);
            map.put("message","浏览次数增加成功");
            response.addCookie(cookie);

            return map;
        }

        map.put("state",false);
        map.put("message","浏览次数增加失败");
        return map;
    }


}




